package me.shiqiang.im.server;

import com.corundumstudio.socketio.SocketIOClient;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author cuishiqiang
 * @date 2017/12/5 下午8:17
 */
public class ConnectionContext {
    private static ConnectionContext ourInstance = new ConnectionContext();

    private static ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();

    public static ConnectionContext getInstance() {
        return ourInstance;
    }

    private ConnectionContext() {
    }

    public String get(String userId) {
        return map.get(userId);
    }

    public String put(String userId, String clientId) {
        return map.put(userId, clientId);
    }

    public void remove(String userId) {
        map.remove(userId);
    }

    public boolean contains(String userId) {
        return map.containsKey(userId);
    }

    private static Map<String,SocketIOClient> processors = new HashMap<>();

    public void putProcessor(SocketIOClient processor){
        processors.put(processor.getSessionId().toString(),processor);
    }

    public boolean processorIsEmpty(){
        return processors.isEmpty();
    }

    public boolean isProcessor(SocketIOClient client) {
        return processors.containsKey(client.getSessionId().toString());
    }

    public SocketIOClient nextProcessor(){
        int size = processors.size();
        Random random = new Random();
        int index = random.nextInt(size);
        ArrayList<SocketIOClient> list = new ArrayList<>();
        list.addAll(processors.values());
        return list.get(index);
    }

    public void delete(SocketIOClient processor) {
        processors.remove(processor.getSessionId().toString());
    }
}
